package com.srs.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.srs.model.QStatus;
import com.srs.util.HibernateUtil;

public class QStatusDao {

	final static Logger logger = LoggerFactory.getLogger(QStatusDao.class);

	private List<QStatus> qStatusList;
	private QStatus qStatus;

	public void delete(Integer id) {

		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			qStatus = (QStatus) session.get(QStatus.class, id);
			session.delete(qStatus);
			tx.commit();

		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<QStatus> list() {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			qStatusList = session.createQuery("from User").list();
			return qStatusList;

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}

	}

	public QStatus get(Integer id) {
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			// change query for get proper data
			Query q = session.createQuery("from User u where u.uid=:id");
			q.setInteger("userid", id);
			return (QStatus) q.uniqueResult();
		} finally {
			session.close();
		}

	}

	public QStatus getNewest(String msisdn){
		Session session = HibernateUtil.getSession();
		try {
			session.beginTransaction();
			Query q = session.createQuery("from QStatus qs where qs.msisdn=:msisdn order by qs.insertedTime desc");
			q.setString("msisdn", msisdn);
			qStatusList = q.list();
			
			if (qStatusList==null) return null;
			return qStatusList.get(0);

		} catch (Exception e) {
			System.out.print("Error while fetching " + e);
			return null;
		} finally {
			session.close();
		}		
	}
	
	public void insert(QStatus qStatus) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(qStatus);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

	public void update(QStatus qStatus) {
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(qStatus);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

	}

}
